package com.nowcoder.community.util;

import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

/**
 * @author szq
 * @create 2023-01-19 19:35
 * @description 使用 JavaMailSender 发送邮件
 */
@Component
public class MailClient {
    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

    @Resource
    private JavaMailSender mailSender;

    // 将yml的属性注入到from
    @Value("${spring.mail.username}")
    private String from;

    public void sendMail(String to, String subject, String content) {
        try {
            // MimeMessage用于封装邮件相关信息
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            // 需要一个邮件帮助器，负责构建MimeMessage对象
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setFrom(from);   // 发件人
            helper.setTo(to);       // 接收人
            helper.setSubject(subject); // 主题
            // 支持HTML文本
            helper.setText(content, true);
            // 发送邮件都有JavaMailSender来做
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            logger.error("发送邮件失败：" + e.getMessage());
        }
    }
}
